# 指定文件编码为UTF-8
# coding: utf-8

"""
deep_convnet.py 功能说明：
1. 实现一个深度卷积神经网络(Deep Convolutional Network)
2. 网络结构包含6个卷积层和3个池化层，最后接全连接层和Dropout
3. 使用ReLU激活函数和He初始化方法
4. 支持前向传播、反向传播、参数保存/加载等功能
5. 设计目标是在MNIST数据集上达到99%以上的识别准确率

网络结构详细说明：
conv1 - relu - conv2 - relu - pool1 -
conv3 - relu - conv4 - relu - pool2 -
conv5 - relu - conv6 - relu - pool3 -
affine1 - relu - dropout - affine2 - dropout - softmax

关键点：
- 使用多层小卷积核(3x3)堆叠代替大卷积核
- 每两个卷积层后接一个2x2最大池化层
- 使用Dropout防止过拟合(全连接层dropout率0.5)
- 采用He初始化方法配合ReLU激活函数
- 支持训练和测试两种模式(Dropout只在训练时生效)
"""

# 导入系统模块
import sys, os
# 添加父目录到系统路径
sys.path.append(os.pardir)
# 导入pickle模块用于参数序列化
import pickle
# 导入NumPy数值计算库
import numpy as np
# 导入有序字典类
from collections import OrderedDict
# 从common.layers导入所有网络层
from common.layers import *

class DeepConvNet:
    """高精度深度卷积神经网络类

    参数说明:
    ----------
    input_dim : 输入数据维度(通道, 高, 宽)
    conv_param_1 ~ conv_param_6 : 各卷积层的参数
        filter_num: 滤波器数量
        filter_size: 滤波器尺寸
        pad: 填充大小
        stride: 步长
    hidden_size: 全连接层神经元数量
    output_size: 输出层神经元数量
    """
    def __init__(self, input_dim=(1, 28, 28),
                 conv_param_1 = {'filter_num':16, 'filter_size':3, 'pad':1, 'stride':1},
                 conv_param_2 = {'filter_num':16, 'filter_size':3, 'pad':1, 'stride':1},
                 conv_param_3 = {'filter_num':32, 'filter_size':3, 'pad':1, 'stride':1},
                 conv_param_4 = {'filter_num':32, 'filter_size':3, 'pad':2, 'stride':1},
                 conv_param_5 = {'filter_num':64, 'filter_size':3, 'pad':1, 'stride':1},
                 conv_param_6 = {'filter_num':64, 'filter_size':3, 'pad':1, 'stride':1},
                 hidden_size=50, output_size=10):
        # 初始化权重参数 ====# ... 省略其他代码 ...


# ==== 修改后代码 ====
        # 计算各层前驱节点数量(用于He初始化)
        pre_node_nums = np.array([1*3*3, 16*3*3, 16*3*3, 32*3*3, 32*3*3, 64*3*3, 64*4*4, hidden_size])
        # 计算各层权重初始化标准差(He初始化)
        wight_init_scales = np.sqrt(2.0 / pre_node_nums)

        self.params = {}
        pre_channel_num = input_dim[0]  # 输入通道数
        # 初始化6个卷积层的权重和偏置
        for idx, conv_param in enumerate([conv_param_1, conv_param_2, conv_param_3,
                                        conv_param_4, conv_param_5, conv_param_6]):
            self.params['W' + str(idx+1)] = wight_init_scales[idx] * np.random.randn(
                conv_param['filter_num'], pre_channel_num,
                conv_param['filter_size'], conv_param['filter_size'])
            self.params['b' + str(idx+1)] = np.zeros(conv_param['filter_num'])
            pre_channel_num = conv_param['filter_num']  # 更新通道数为当前层滤波器数量

        # 初始化全连接层权重和偏置
        self.params['W7'] = wight_init_scales[6] * np.random.randn(64*4*4, hidden_size)
        self.params['b7'] = np.zeros(hidden_size)
        self.params['W8'] = wight_init_scales[7] * np.random.randn(hidden_size, output_size)
        self.params['b8'] = np.zeros(output_size)

        # 构建网络层 ====# ... 省略其他代码 ...


# ==== 修改后代码 ====
        self.layers = []
        # 第1个卷积块(conv1-relu-conv2-relu-pool1)
        self.layers.append(Convolution(self.params['W1'], self.params['b1'],
                           conv_param_1['stride'], conv_param_1['pad']))
        self.layers.append(Relu())
        self.layers.append(Convolution(self.params['W2'], self.params['b2'],
                           conv_param_2['stride'], conv_param_2['pad']))
        self.layers.append(Relu())
        self.layers.append(Pooling(pool_h=2, pool_w=2, stride=2))

        # 第2个卷积块(conv3-relu-conv4-relu-pool2)
        self.layers.append(Convolution(self.params['W3'], self.params['b3'],
                           conv_param_3['stride'], conv_param_3['pad']))
        self.layers.append(Relu())
        self.layers.append(Convolution(self.params['W4'], self.params['b4'],
                           conv_param_4['stride'], conv_param_4['pad']))
        self.layers.append(Relu())
        self.layers.append(Pooling(pool_h=2, pool_w=2, stride=2))

        # 第3个卷积块(conv5-relu-conv6-relu-pool3)
        self.layers.append(Convolution(self.params['W5'], self.params['b5'],
                           conv_param_5['stride'], conv_param_5['pad']))
        self.layers.append(Relu())
        self.layers.append(Convolution(self.params['W6'], self.params['b6'],
                           conv_param_6['stride'], conv_param_6['pad']))
        self.layers.append(Relu())
        self.layers.append(Pooling(pool_h=2, pool_w=2, stride=2))

        # 全连接部分(affine1-relu-dropout-affine2-dropout)
        self.layers.append(Affine(self.params['W7'], self.params['b7']))
        self.layers.append(Relu())
        self.layers.append(Dropout(0.5))  # dropout率0.5
        self.layers.append(Affine(self.params['W8'], self.params['b8']))
        self.layers.append(Dropout(0.5))

        # 最后一层: SoftmaxWithLoss
        self.last_layer = SoftmaxWithLoss()

    def predict(self, x, train_flg=False):
        """前向传播计算输出"""
        for layer in self.layers:
            if isinstance(layer, Dropout):
                x = layer.forward(x, train_flg)  # Dropout层区分训练/测试模式
            else:
                x = layer.forward(x)
        return x

    def loss(self, x, t):
        """计算损失函数值"""
        y = self.predict(x, train_flg=True)  # 训练模式启用Dropout
        return self.last_layer.forward(y, t)

    def accuracy(self, x, t, batch_size=100):
        """计算分类准确率"""
        if t.ndim != 1 : t = np.argmax(t, axis=1)  # one-hot转标签

        acc = 0.0
        # 分批计算避免内存不足
        for i in range(int(x.shape[0] / batch_size)):
            tx = x[i*batch_size:(i+1)*batch_size]
            tt = t[i*batch_size:(i+1)*batch_size]
            y = self.predict(tx, train_flg=False)  # 测试模式关闭Dropout
            y = np.argmax(y, axis=1)
            acc += np.sum(y == tt)

        return acc / x.shape[0]

    def gradient(self, x, t):
        """误差反向传播法计算梯度"""
        # 前向传播
        self.loss(x, t)

        # 反向传播
        dout = 1  # 初始化梯度
        dout = self.last_layer.backward(dout)

        # 各层反向传播
        tmp_layers = self.layers.copy()
        tmp_layers.reverse()  # 反转层顺序
        for layer in tmp_layers:
            dout = layer.backward(dout)

        # 收集各层梯度
        grads = {}
        # 各权重层在self.layers中的索引位置
        weight_layer_indices = (0, 2, 5, 7, 10, 12, 15, 18)
        for i, layer_idx in enumerate(weight_layer_indices):
            grads['W' + str(i+1)] = self.layers[layer_idx].dW
            grads['b' + str(i+1)] = self.layers[layer_idx].db

        return grads

    def save_params(self, file_name="params.pkl"):
        """保存网络参数到文件"""
        params = {}
        for key, val in self.params.items():
            params[key] = val
        with open(file_name, 'wb') as f:
            pickle.dump(params, f)  # 序列化参数

    def load_params(self, file_name="params.pkl"):
        """从文件加载网络参数"""
        with open(file_name, 'rb') as f:
            params = pickle.load(f)  # 反序列化参数
        # 更新网络参数
        for key, val in params.items():
            self.params[key] = val

        # 更新各层参数
        weight_layer_indices = (0, 2, 5, 7, 10, 12, 15, 18)
        for i, layer_idx in enumerate(weight_layer_indices):
            self.layers[layer_idx].W = self.params['W' + str(i+1)]
            self.layers[layer_idx].b = self.params['b' + str(i+1)]

"""
使用说明：
1. 实例化网络：
   net = DeepConvNet()
2. 训练网络：
   - 前向传播：y = net.predict(x, train_flg=True)
   - 计算损失：loss = net.loss(x, t)
   - 计算梯度：grads = net.gradient(x, t)
3. 测试网络：
   - 预测：y = net.predict(x, train_flg=False)
   - 计算准确率：acc = net.accuracy(x, t)
4. 保存/加载参数：
   - net.save_params()
   - net.load_params()
"""
